package pl.com.like.sequoia.maintenance;

import java.io.File;
import java.text.MessageFormat;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import pl.com.like.sequoia.biojava.util.ILocalFileImporter;
import pl.com.like.sequoia.exceptions.LogicalException;

@Component
public class PdbResourcesImporter {

	private final Logger log = LoggerFactory.getLogger(PdbResourcesImporter.class);

	private String dirPath;
	@Autowired
	private ILocalFileImporter localFileImporter;
	@Autowired
	private IDirScanner dirScanner;

	public String getDirPath() {
		return dirPath;
	}

	public IDirScanner getDirScanner() {
		return dirScanner;
	}

	public ILocalFileImporter getLocalFileImporter() {
		return localFileImporter;
	}

	public void process() throws LogicalException {
		File basedir = new File(dirPath);
		if (basedir.exists()) {
			Set<File> files = dirScanner.scan(basedir);
			for (File fItem : files) {
				try {
					localFileImporter.setObject(fItem);
				} catch (LogicalException e) {
					log.warn(MessageFormat.format("while saving file {0} into DB thrown exception", fItem
							.getAbsolutePath()), e);
				}
			}
		} else {
			throw new LogicalException(MessageFormat.format("given path {0} does not exists on filesystem", dirPath));
		}
	}

	public void setDirPath(String dirPath) {
		this.dirPath = dirPath;
	}

	public void setDirScanner(IDirScanner dirScanner) {
		this.dirScanner = dirScanner;
	}

	public void setLocalFileImporter(ILocalFileImporter localFileImporter) {
		this.localFileImporter = localFileImporter;
	}
}
